'use strict'
require('./index.scss')
require('page/common/nav/index.js')
require('page/common/header/index.js')
var navSide = require('page/common/nav-side/index.js')
// 通用的JS工具封装
var _wm = require('util/wm.js')
// 用户服务
var _user = require('service/user-service.js')

var templateIndex = require('./index.string')


var page = {
    init: function(){
        this.onLoad()
        this.bindEvent()
    },

    onLoad: function(){
        // 初始化左侧菜单
        navSide.init({
            name: 'user-center'
        })
        this.loadUserInfo()
    },

    // 加载个人中心-用户信息
    loadUserInfo: function(){
        var userHtml = ''

        _user.getUserInfo(function(res){
            userHtml = _wm.render(templateIndex, res)
            $('.panel_body').html(userHtml)
        }, function(errMsg){
            _wm.errorTips(errMsg)
        })
    },

    bindEvent: function(){
        var that = this

        // 点击提交按钮后的动作，事件冒泡
        $(document).on('click', '.btn_submit', function(){
            var userInfo = {
                phone : $.trim($('#phone').val()),
                email: $.trim($('#email').val()),
                question: $.trim($('#question').val()),
                answer: $.trim($('#answer').val())
            },
            validateResult = that.validateForm(userInfo)
            if(validateResult.status){
                // 更改用户信息
                _user.updateUserInfo(userInfo, function(res, msg){
                    _wm.successTips(msg)
                    window.location.href = './user-center.html'
                }, function(errMsg){
                    _wm.errorTips(errMsg)
                })
            }else{
                _wm.errorTips(validateResult.msg)
            }
        })
    },
    
    // 验证字段信息
    validateForm: function(formData){
        // 返回的验证结果
        var result = {
            status: false,
            msg: ''
        }
        // 验证手机号格式
        if(!_wm.validate(formData.phone, 'phone')){
            result.msg = '手机号格式不正确'
            return result
        }
        // 验证邮箱格式
        if(!_wm.validate(formData.email, 'email')){
            result.msg = '邮箱格式不正确'
            return result
        }
        // 验证密码提示问题是否为空
        if(!_wm.validate(formData.question, 'require')){
            result.msg = '密码提示问题不能为空'
            return result
        }
        // 验证提示问题答案是否为空
        if(!_wm.validate(formData.answer, 'require')){
            result.msg = '密码提示问题答案不能为空'
            return result
        }

        // 验证通过，返回正确提示
        return result = {
            status: true,
            msg: '验证通过'
        }
    }
}

$(function(){
    page.init()
})